package com.party.web.web.controller.member;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.article.Article;
import com.party.core.model.commune.CNotebook;
import com.party.core.model.commune.CNotebookType;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.article.impl.ArticleService;
import com.party.core.service.commune.ICNotebookService;
import com.party.core.service.commune.ICNotebookTypeService;
import com.party.core.service.member.IMemberGroupService;
import com.party.web.biz.article.ArticleBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.input.member.CNotebookInput;
import com.party.web.web.dto.input.member.CNotebookTypeInput;
import com.party.web.web.dto.output.member.CNotebookOutput;
import com.party.web.web.dto.output.member.CNotebookTypeOutput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: party
 * @description: 笔记本控制器
 * @author: Hua Qunhao
 * @create: 2019-12-26 10:34
 **/
@Controller
@RequestMapping(value = "member/notebook")
public class NotebookController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ICNotebookService notebookService;

    @Autowired
    private ICNotebookTypeService notebookTypeService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleBizService articleBizService;


    /**
     * @Description: 笔记本列表
     * @Param: [moment, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("/list")
    public ModelAndView list(CNotebookInput notebookInput, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/material/notebookList");

        Map<String, Object> params = CommonInput.appendParams(input);
        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }
        mv.addObject("input", input);

        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        List<MemberGroup> memberGroupList = new ArrayList<>();
        List<String> orgIds = Lists.newArrayList();
        if (!Constant.MEMBER_XZGSADMIN.equals(currentUser.getType())) {
            if (!currentUser.isChild()) { //行知公社
                memberGroupList = memberGroupService.getChildList(currentUser.getId());
                params.put("createBy", currentUser.getId());
            } else {
                orgIds = new ArrayList<>();
                orgIds.add(currentUser.getId());
            }
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), null);
        }
        if (StringUtils.isNotEmpty(notebookInput.getMemberGroupId())) {
            orgIds = new ArrayList<>();
            List<MemberGroup> memberGroupList_query = memberGroupService.getChildWithMyAndName(notebookInput.getMemberGroupId());
            orgIds = LangUtils.transform(memberGroupList_query, input1 -> input1.getId());
        }
        if (StringUtils.isNotEmpty(notebookInput.getName())) {
            params.put("name", notebookInput.getName());
        }
        params.put("orgIds", orgIds);
        List<CNotebook> notebooks = notebookService.webListPage(params, page);
        List<CNotebookOutput> outputs = LangUtils.transform(notebooks, notebook -> {
            CNotebookOutput output = CNotebookOutput.transform(notebook);

            MemberGroup memberGroup = memberGroupService.get(notebook.getMemberGroupUserId());
            if (memberGroup != null) {
                MemberGroup memberGroupUser = memberGroupService.get(memberGroup.getPartnerId());
                output.setMemberGroupName(memberGroup.getRealname());
                output.setMemberGroupUserName(memberGroup.getRealname() + " / " + memberGroup.getUsername());
            }


            CNotebookType cNotebookType = new CNotebookType();
            cNotebookType.setNotebookId(notebook.getId());
            Integer notebookTypeNum = notebookTypeService.getCNotebookTypeCount(cNotebookType);
            Integer materialTypeNum = notebookService.getCMaterialCount(null, notebook.getId());
            output.setNotebookTypeNum(notebookTypeNum);
            output.setMaterialTypeNum(materialTypeNum);
            return output;
        });
        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        mv.addObject("notebookInput", notebookInput);
        mv.addObject("notebooks", outputs);
        mv.addObject("page", page);
        return mv;
    }


    /**
     * @Description:笔记本详情
     * @Param: [id]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("form")
    public ModelAndView form(String id) {
        ModelAndView mv = new ModelAndView("member/material/notebookForm");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        List<MemberGroup> memberGroups = new ArrayList<>();
        if (currentUser.isXzgsAdmin()) {
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), null);
        } else {
            memberGroups = memberGroupService.getChildList(currentUser.getId());
        }

        CNotebook notebook = null;
        String memberGroupUserId = null;
        String memberGroupId = null;
        if (StringUtils.isNotEmpty(id)) {
            notebook = notebookService.get(id);
            memberGroupUserId = notebook.getMemberGroupUserId();
            memberGroupId = notebook.getMemberGroupId();
        }

        mv.addObject("notebook", notebook);
        mv.addObject("memberGroupUserId", memberGroupUserId);
        mv.addObject("memberGroupId", memberGroupId);
        mv.addObject("memberGroupList", memberGroups);
        return mv;
    }

    /**
     * @Description:笔记本保存
     * @Param: [input]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "save")
    public AjaxResult save(CNotebookInput input) {
        if (StringUtils.isEmpty(input.getMemberGroupUserId()) || StringUtils.isEmpty(input.getName())) {
            return AjaxResult.error("参数为空");
        }
        try {
            CNotebook queryCnotebookOrg = new CNotebook();
            queryCnotebookOrg.setMemberGroupUserId(input.getMemberGroupUserId());
            List<CNotebook> list = notebookService.list(queryCnotebookOrg);
            if (list.size() > 0) {
                CNotebook dbcnotebookOrg = list.get(0);
                if (!dbcnotebookOrg.getMemberGroupUserId().equals(input.getMemberGroupUserId())) {
                    return AjaxResult.error("一个用户只能分配一个笔记本");
                }
            }
            if (StringUtils.isEmpty(input.getId())) {
                MemberGroup memberGroup = memberGroupService.get(input.getMemberGroupId());
                CNotebook cNotebook = new CNotebook();
                cNotebook.setName(input.getName());
                cNotebook.setMemberGroupId(input.getMemberGroupId());
                cNotebook.setMemberGroupUserId(input.getMemberGroupUserId());
                cNotebook.setCreateBy(memberGroup.getPartnerId());
                cNotebook.setUpdateBy(memberGroup.getCreateBy());
                notebookService.insert(cNotebook);
            } else {
                CNotebook cNotebook = notebookService.get(input.getId());
                cNotebook.setMemberGroupUserId(input.getMemberGroupUserId());
                cNotebook.setMemberGroupId(input.getMemberGroupId());
                cNotebook.setName(input.getName());
                notebookService.update(cNotebook);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * @Description:笔记本删除
     * @Param: [input]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("参数为空");
        }
        try {
            CNotebook cNotebook = notebookService.get(id);
            if (cNotebook == null) {
                return AjaxResult.error("笔记本为空");
            }
            CNotebookType cNotebookType = new CNotebookType();
            cNotebookType.setNotebookId(id);
            List<CNotebookType> list = notebookTypeService.list(cNotebookType);
            if (list.size() > 0) {
                return AjaxResult.error("笔记本下存在类型，不能直接删除");
            }
            notebookService.delete(id);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * @Description: 笔记本类型列表
     * @Param: [moment, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("type/list")
    public ModelAndView typeList(CNotebookTypeInput notebookTypeInput, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/material/notebookTypeList");
        List<CNotebook> notebooks = null;
        Map<String, Object> params = CommonInput.appendParams(input);

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }
        mv.addObject("input", input);

        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        if (!currentUser.isChild()) {
            notebooks = notebookService.list(null);
        } else if (Constant.MEMBER_XZGSADMIN.equals(currentUser.getType())) {
            notebooks = notebookService.webListPage(null, null);
        } else {
            params.put("memberGroupUserId", currentUser.getId());
        }

        params.put("notebookId", notebookTypeInput.getNotebookId());
        params.put("notebookName", notebookTypeInput.getNotebookName());
        params.put("name", notebookTypeInput.getName());

        List<CNotebookType> notebookTypes = notebookTypeService.webListPage(params, page);
        List<CNotebookTypeOutput> outputs = LangUtils.transform(notebookTypes, notebookType -> {
            CNotebookTypeOutput output = CNotebookTypeOutput.transform(notebookType);
            Integer materialTypeNum = notebookService.getCMaterialCount(notebookType.getId(), null);
            output.setMaterialTypeNum(materialTypeNum);
            return output;
        });

        mv.addObject("notebookTypeInput", notebookTypeInput);
        mv.addObject("notebookTypes", outputs);
        mv.addObject("notebooks", notebooks);
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        mv.addObject("page", page);
        return mv;
    }

    /**
     * @Description:笔记本类型详情
     * @Param: [id]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("type/form")
    public ModelAndView typeForm(String notebookId, String id) {
        ModelAndView mv = new ModelAndView("member/material/notebookTypeForm");
        List<CNotebook> notebooks = null;
        if (RealmUtils.getNewCurrentUser().isXzgsAdmin()) {
            notebooks = notebookService.webListPage(null,null);
        } else {
            notebooks = notebookService.list(null);
        }
        CNotebookType notebookType = null;
        if (StringUtils.isNotEmpty(id)) {
            notebookType = notebookTypeService.get(id);
            if (StringUtils.isEmpty(notebookId)) {
                notebookId = notebookType.getNotebookId();
            }
        }
        mv.addObject("notebooks", notebooks);
        mv.addObject("notebookId", notebookId);
        mv.addObject("notebookType", notebookType);
        return mv;
    }

    /**
     * @Description:笔记本类型保存
     * @Param: [input]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "type/save")
    public AjaxResult typeSave(CNotebookTypeInput input) {
        if (StringUtils.isEmpty(input.getNotebookId()) || StringUtils.isEmpty(input.getName())) {
            return AjaxResult.error("参数为空");
        }
        CNotebook cNotebook = notebookService.get(input.getNotebookId());
        try {
            if (StringUtils.isEmpty(input.getId())) {
                CNotebookType cNotebookType = new CNotebookType();
                cNotebookType.setName(input.getName());
                cNotebookType.setNotebookId(input.getNotebookId());
                cNotebookType.setSort(input.getSort());
                cNotebookType.setCreateBy(cNotebook.getMemberGroupUserId());
                cNotebookType.setUpdateBy(cNotebook.getMemberGroupUserId());
                notebookTypeService.insert(cNotebookType);
            } else {
                CNotebookType cNotebookType = notebookTypeService.get(input.getId());
                cNotebookType.setName(input.getName());
                cNotebookType.setSort(input.getSort());
                cNotebookType.setNotebookId(input.getNotebookId());
                cNotebookType.setUpdateBy(cNotebook.getMemberGroupUserId());
                notebookTypeService.update(cNotebookType);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("保存成功", input.getNotebookId());
    }

    /**
     * @Description:笔记本类型删除
     * @Param: [input]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "type/delete")
    public AjaxResult typeDelete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("参数为空");
        }
        try {
            CNotebookType cNotebookType = notebookTypeService.get(id);
            if (cNotebookType == null) {
                return AjaxResult.error("笔记本类型不存在");
            }
            Integer materialTypeNum = notebookService.getCMaterialCount(cNotebookType.getId(), null);
            if (materialTypeNum != 0) {
                return AjaxResult.error("该笔记本类型下存在素材，不能直接删除");
            }
            notebookTypeService.delete(id);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 前端分社下级分类联动
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getnotebookTyperByNotebookId")
    public AjaxResult getnotebookTyperByNotebookId(String notebookId) {
        if (StringUtils.isEmpty(notebookId)) {
            return AjaxResult.error("参数为空");
        }
        List<CNotebookType> cNotebookTypes = Lists.newArrayList();
        CNotebookType cNotebookType = new CNotebookType();
        cNotebookType.setNotebookId(notebookId);
        cNotebookTypes = notebookTypeService.list(cNotebookType);
        return AjaxResult.success(cNotebookTypes);
    }

    /**
     * @Description:笔记本详情
     * @Param: [id]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("copyForm")
    public ModelAndView copyForm(String id) {
        ModelAndView mv = new ModelAndView("member/material/notebookcopyForm");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        List<MemberGroup> memberGroups = new ArrayList<>();
        if (currentUser.isXzgsAdmin()) {
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), null);
        } else {
            memberGroups = memberGroupService.getChildList(currentUser.getId());
        }

        CNotebook notebook = null;
        String memberGroupUserId = null;
        String memberGroupId = null;
        if (StringUtils.isNotEmpty(id)) {
            notebook = notebookService.get(id);
        }

        mv.addObject("notebook", notebook);
        mv.addObject("memberGroupUserId", memberGroupUserId);
        mv.addObject("memberGroupId", memberGroupId);
        mv.addObject("memberGroupList", memberGroups);
        return mv;
    }


    /**
     * @Description:笔记本保存
     * @Param: [input]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "copySave")
    public AjaxResult copySave(CNotebookInput input) {
        if (StringUtils.isEmpty(input.getMemberGroupUserId()) || StringUtils.isEmpty(input.getName()) || StringUtils.isEmpty(input.getId())) {
            return AjaxResult.error("参数为空");
        }
        try {
            CNotebook queryCnotebookOrg = new CNotebook();
            queryCnotebookOrg.setMemberGroupUserId(input.getMemberGroupUserId());
            List<CNotebook> list = notebookService.list(queryCnotebookOrg);
            if (list.size() > 0) {
                return AjaxResult.error("一个用户只能分配一个笔记本");
            }
            //笔记本复制
            MemberGroup memberGroup = memberGroupService.get(input.getMemberGroupId());
            CNotebook cNotebook = new CNotebook();
            cNotebook.setName(input.getName());
            cNotebook.setMemberGroupId(input.getMemberGroupId());
            cNotebook.setMemberGroupUserId(input.getMemberGroupUserId());
            cNotebook.setCreateBy(memberGroup.getPartnerId());
            cNotebook.setUpdateBy(memberGroup.getCreateBy());
            notebookService.insert(cNotebook);
            //笔记本类型复制
            CNotebookType cNotebookType = new CNotebookType();
            cNotebookType.setNotebookId(input.getId());
            List<CNotebookType> list1 = notebookTypeService.list(cNotebookType);
            for (CNotebookType typeOrg : list1) {
                String typeId = typeOrg.getId();
                typeOrg.setId(null);
                typeOrg.setNotebookId(cNotebook.getId());
                notebookTypeService.insert(typeOrg);

                //素材复制
                Article article = new Article();
                article.setNotebookTypeId(typeId);
                List<Article> list2 = articleService.list(article);
                for (Article artOrg : list2) {
                    artOrg.setId(null);
                    artOrg.setNotebookId(cNotebook.getId());
                    artOrg.setNotebookTypeId(typeOrg.getId());
                    articleService.insert(artOrg);
                    try {
                        articleBizService.uploadQrCode(artOrg.getMemberId(), article.getId());
                    } catch (Exception e) {
                        logger.error("生成文章二维码异常", e);
                    }
                }
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }
}
